package com.softWang.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.softWang.common.exception.ErrorCode;
import com.softWang.common.response.ResponseResult;
import com.softWang.common.utils.SecurityUtils;
import com.softWang.common.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问一个需要认证的 URL 资源，已经认证（登录）但是没有权限的情况下，返回 403 错误
 */
@Component
@Slf4j
public class AccessDeniedHandlerMyImpl implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException, ServletException {
        // 打印 warn 的原因是，不定期合并 warn，看看有没恶意破坏
        log.warn("[commence][访问 URL({}) 时，用户({}) 权限不够]", request.getRequestURI(),
                SecurityUtils.getUserId(), e);
        // 返回 403
        String msg = objectMapper.writeValueAsString(ResponseResult.failure(ErrorCode.FORBIDDEN));
        WebUtils.renderString(response, msg);
    }

}
